<template>
  <div class="Carousel-container" ref="container" @mousemove="handleMouseIn" :style="imagePosition">
    <!-- <img :src="url" :title="desc"> -->
    <div class="carousel-img" ref="inner">
      <ImageLoader :src="url" :placeholder="placeholder" :duration="1200"></ImageLoader>
    </div>
  </div>
</template>

<script>
import ImageLoader from '@/components/ImageLoader'
export default {
  components: {
    ImageLoader
  },
  props: {
    url: {
      type: String,
      reuqired: true
    },
    placeholder: {
      type: String,
      reuqired: true
    },
    desc: {
      type: String,
      reuqired: true
    },
  },
  data() {
    return {
      containerSize: null, // 外层容器
      innerSize: null,   // 内部图片
      mouseX: 0,
      mouseY: 0
    }
  },
  computed: {
    center() {
      return {
        x: this.containerSize.width / 2,
        y: this.containerSize.height / 2,
      }
    },
    imagePosition() {
      if (!this.innerSize || !this.containerSize) return
      const extraWidth = this.innerSize.width - this.containerSize.width; // 多出的宽度
      const extraHeight = this.innerSize.height - this.containerSize.height; //多出的高度
      const left = (-extraWidth / this.containerSize.width) * this.mouseX;
      const top = (-extraHeight / this.containerSize.height) * this.mouseY;

      return {
        left: left + 'px',
        top: top + 'px',
      }
    }
  },
  mounted() {
    this.setSize()
    this.mouseX = this.center.x
    this.mouseY = this.center.y
    window.addEventListener('resize', this.setSize)
  },
  methods: {
    setSize() {
      this.containerSize = {
        width: this.$refs.container.clientWidth,
        height: this.$refs.container.clientHeight
      }
      this.innerSize = {
        width: this.$refs.inner.clientWidth,
        height: this.$refs.inner.clientHeight
      }
    },
    handleMouseIn(e) {
      const rect = this.$refs.container.getBoundingClientRect();
      this.mouseX = e.clientX - rect.left;
      this.mouseY = e.clientY - rect.top;
    },
    handleMouseOut() {
      this.mouseX = 0
      this.mouseY = 0
    }
  },
  destroyed() {
    window.removeEventListener('resize', this.setSize)
  }
}
</script>

<style lang="less" scoped>
.Carousel-container {
  width: 100%;
  height: 100%;
  opacity: 0.5;
  position: relative;
  .carousel-img {
    width: 110%;
    height: 110%;
    position: absolute;
    top: 0;
    left: 0;
    z-index: -1;
    transition: 300ms linear;
  }
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}
</style>